package com.gjh.study.mybatis;

import java.io.IOException;
import java.io.InputStream;

import com.gjh.study.mybatis.domain.Student;
import com.gjh.study.mybatis.mapper.PersonMapper;
import com.gjh.study.mybatis.domain.Person;
import com.gjh.study.mybatis.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

/**
 * @author guangjh
 * @version 1.0
 * @date 2020/7/10 20:40
 */
public class App {
    private static Logger logger = Logger.getLogger(App.class);

    public static void main(String[] args) throws IOException {
        // 1. 读取 mybatis-config.xml 文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        // 2. 初始化 mybatis，创建 SqlSessionFactory 实例
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 3. 创建 SqlSession 实例
        SqlSession session = sqlSessionFactory.openSession();
        // 4. 操作数据库
        // 方法一： 获取 xml 映射文件中定义的操作语句
        Person p = session.selectOne("com.gjh.study.mybatis.mapper.PersonMapper.selectPersonById", 1l);
        logger.info(p);

        // 方法二： 获取 mapper 接口的代理对象
        StudentMapper sm = session.getMapper(StudentMapper.class);
        // 直接调用接口的方法，查询 id 为 1 的 Person 数据
        Student s = sm.getStudent(1l);
        logger.info(s);

        // 提交事务
        session.commit();
        // 关闭 session
        session.close();
    }
}
